package db

import (
	"database/sql"
	"fmt"
	"time"

	"gitee.com/hp-huiw/my-go-core/config"
	_ "github.com/go-sql-driver/mysql"
)

func GetDB() *sql.DB {
	dsn := config.ConfigLoader.GetAppConfig().DataSource.Dsn

	db, err := sql.Open("mysql", dsn)
	panicOnError(err)

	// Total connections allowed
	db.SetMaxOpenConns(50)

	// How many idle connections kept in pool
	db.SetMaxIdleConns(10)

	// Go will recycle the connection before MySQL times it out → avoids stale connection errors like “unexpected sequence nr”.
	// MySQL timeout error: [mysql] [warn] unexpected sequence nr: expected 1, got 0
	// It must be < MySQL wait_timeout (default 8h)
	db.SetConnMaxLifetime(2 * time.Hour)

	// Optional: Ping to verify DSN works at startup

	if err := db.Ping(); err != nil {
		panic(fmt.Sprintf("Db ping failed: %v", err))
	}

	return db
}

func panicOnError(err error) {
	if err != nil {
		panic(fmt.Sprintf("Db connecting failed on %v. Error: %v", config.ConfigLoader.GetAppConfig().DataSource.Dsn, err.Error()))
	}
}
